<template>
  <div id="talent_02">
    <p class="data_time">
      <span>数据更新时间：</span>
      <span style="color:#888">{{ timestamp(time, "Y-M-D h:m") }}</span>
    </p>
    <section class="type mt_30">
      <time_options
        v-model="value03"
        :radio_values="['日榜', '周榜', '月榜']"
      />
      <section class="input_group">
        <input
          type="text"
          v-model="input01"
          placeholder="请输入关键词在排行榜中搜索"
          @keyup.enter="search_input()"
        />
        <div @click="search_input()" class="imgBox">
          <!-- <img src="../../../assets/meng/search01.png" /> -->
        </div>
      </section>
      <div class="btn_group">
        <button @click="generatorImage">
          <img src="../../../assets/meng/star_map05.png" />分享
        </button>
        <button @click="export_data">
          <img src="../../../assets/meng/star_map04.png" />导出
        </button>
      </div>
    </section>
    <ul
      class="fixedThead"
      ref="fixedThead"
      :class="{ isShow: isFixed }"
      :style="showLeft == true ? 'left:222px' : 'left:98px'"
    >
      <li tc>排名</li>
      <li>达人</li>
      <li tc>所属行业</li>
      <li tc>
        音浪收入
        <el-tooltip
          effect="light"
          :hide-after="2000"
          content="统计该周期内结束的直播间音浪收入。"
          placement="bottom-start"
        >
          <img src="../../../assets/meng/search_result04.png" class="tip_img" />
        </el-tooltip>
      </li>
      <li tc>操作</li>
    </ul>
    <table class="table" ref="capture">
      <thead>
        <tr>
          <th style="width:10%">排名</th>
          <th>达人</th>
          <th>所属行业</th>
          <th>
            音浪收入
            <el-tooltip
              effect="light"
              :hide-after="2000"
              content="统计该周期内结束的直播间音浪收入。"
              placement="bottom-start"
            >
              <img
                src="../../../assets/meng/search_result04.png"
                class="tip_img"
              />
            </el-tooltip>
          </th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody v-if="table_data01.length != 0 && !loading">
        <tr
          v-for="(item, index) in table_data01"
          :key="'table' + index"
          :id="!index ? 'tr1' : ''"
        >
          <td class="td td_01">{{ item.rowId }}</td>
          <td class="td td_02">
            <div style="justify-content: flex-start;">
              <img
                :src="item.logo"
                class="pointer"
                @click="go_to_page01(item.authorId)"
              />
              <section>
                <div>
                  <span
                    class="dot pointer"
                    @click="go_to_page01(item.authorId)"
                    >{{ item.nickName }}</span
                  >
                  <img
                    v-if="item.isShop == 1"
                    src="../../../assets/meng/search_result01.png"
                  />
                  <img
                    v-if="item.verifyType == 1"
                    src="../../../assets/meng/search_result02.png"
                  />
                  <img
                    v-if="item.verifyType == 2"
                    src="../../../assets/meng/search_result03.png"
                  />
                </div>
                <div>粉丝数：{{ format_num(item.totalFans) }}</div>
              </section>
            </div>
          </td>
          <td class="td td_03">
            <div>{{ item.categoryName }}</div>
          </td>
          <td class="td td_04">
            <div>{{ format_num(item.soundbyte) }}</div>
          </td>
          <td class="td td_05">
            <button @click="go_to_page01(item.authorId)">查看详情</button>
          </td>
        </tr>
      </tbody>
    </table>

    <div class="upgradeBox" v-if="!permissions">
      <RankUpgrade class="rankUpgrade" />
    </div>
    <p
      class="nothing"
      v-show="
        table_data01.length < 30 &&
          !loading &&
          permissions &&
          table_data01.length != 0
      "
    >
      我是有底线的～
    </p>
    <div class="pageBox" v-if="!loading">
      <el-pagination
        background
        layout="prev, pager, next, jumper"
        :total="count"
        :page-size="30"
        :current-page="page"
        @current-change="get_data"
        :hide-on-single-page="true"
      ></el-pagination>
    </div>

    <div
      v-loading="loading"
      v-if="loading"
      class="loading"
      element-loading-text="拼命加载中..."
      element-loading-spinner="el-icon-loading"
    ></div>

    <div
      class="empty"
      v-show="!loading && table_data01.length == 0 && permissions"
    >
      <img src="@/assets/liu/zw.png" />
      <p>暂无数据</p>
    </div>
  </div>
</template>
<script>
import html2canvas from "html2canvas";
import RankUpgrade from "@/component/rankUpgrade.vue";
export default {
  name: "talent_02",
  components: { RankUpgrade },
  data() {
    return {
      permissions: 1,
      value03: "日榜",
      busy: false,
      loading: true,
      table_data01: [],

      cancel01: null,
      input01: "",
      time: "",
      count: 0,
      page: 1,
      isFixed: false,
      offsetTop: 0,
      showLeft: true
    };
  },
  computed: {
    listen_change() {
      const { value01, value02, value03 } = this;
      return {
        value03
      };
    }
  },
  watch: {
    "$store.state.left_nav_flag"(old, newOld) {
      this.showLeft = newOld;
      if ((newOld = false)) {
        this.setTBBar();
      } else {
        this.setTBBar();
      }
    }
  },
  created() {
    // this.get_data() 因为time_options组件内部已经提交新值，导致v-model的值更改，所以已经执行请求函数
    this.$watch(
      "listen_change",
      this.debounce((newValue, oldValue) => {
        this.page = 1;
        this.table_data01 = [];
        this.get_data();
      }, 0)
    );
  },
  mounted() {
    window.addEventListener("scroll", this.initHeight);
    window.addEventListener("resize", () => {
      //给浏览器窗口绑定变化大小事件
      this.setTBBar();
    });
  },
  methods: {
    // 获取子节点函数（后期可集成到一个库里）
    getChilds(pNode) {
      if (!pNode) return false;
      let nodes = pNode.childNodes;
      let newList = [];
      for (let i = 0; i < nodes.length; i++) {
        let node = nodes[i];
        if (node.nodeType === 1) {
          //判断类型
          newList.push(node);
        }
      }
      return newList;
    },
    // 设置表格表头滑动置顶
    setTBBar() {
      this.$nextTick(() => {
        let tableEl = this.$refs.tableEl;
        let ulEl = this.$refs.fixedThead;
        let tr1 = document.querySelector("#tr1");
        // thTrEl.style.width = tableEl.offsetWidth+'px';
        if (tr1) {
          let tds = this.getChilds(tr1);
          let liEls = this.getChilds(ulEl);

          for (let i = 0; i < liEls.length; i++) {
            liEls[i].style.width = tds[i].offsetWidth + "px";
          }
        }
      });
    },
    search_input() {
      this.page = 1;
      this.table_data01 = [];
      this.get_data();
    },
    get_data(cpage) {
      let that = this;
      if (cpage) {
        that.backTop();
        that.page = cpage;
        //console.log("page", this.page);
      }
      that.loading = true;
      this.permissions = 1;
      that.busy = true;
      that.$axios
        .post(
          "/api/live/PostSoundWaveRank",
          {
            Keyword: that.trimStr(that.input01),
            RankType:
              that.value03.split("?")[0] == "日榜"
                ? 1
                : that.value03.split("?")[0] == "周榜"
                ? 2
                : 3,
            Time: that.value03.split("?")[1],
            Size: 30,
            Index: that.page
          },
          {
            cancelToken: new that.$axios.CancelToken(function executor(c) {
              if (that.cancel01) that.cancel01();
              that.cancel01 = c;
            })
          }
        )
        .then(response => {
          that.loading = false;
          if (response.data.code == 1003) {
            this.permissions = 0;
            this.table_data01 = [];
          } else {
            this.permissions = 1;
          }
          if (response.data.code == 0) {
            this.setTBBar();
            // console.log(response.data.data)
            that.time = response.data.data.timespan;

            that.table_data01 = response.data.data.ranks;

            that.count = response.data.data.totalCount;

            response.data.data.ranks.length < 30
              ? (that.busy = true)
              : (that.busy = false);
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    generatorImage() {
      var that = this;
      const loading = this.$loading({
        lock: true,
        text: "导出中...",
        spinner: "el-icon-loading",
        customClass: "customClass"
      });
      var shareContent;
      shareContent = this.$refs.capture; //需要截图的包裹的（原生的）DOM 对象
      var width = shareContent.offsetWidth; //获取dom 宽度
      var height = shareContent.offsetHeight; //获取dom 高度
      var canvas = document.createElement("canvas"); //创建一个canvas节点
      //   var scale = window.devicePixelRatio //定义任意放大倍数 支持小数 //   var scale = 2 //定义任意放大倍数 支持小数
      var scale = 1;
      canvas.width = width * scale * scale; //定义canvas 宽度 * 缩放
      canvas.height = height * scale * scale; //定义canvas高度 *缩放
      canvas.style.width = width + "px";
      canvas.style.height = height + "px";
      canvas.getContext("2d").scale(scale, scale); //获取context,设置scale
      var opts = {
        dpi: window.devicePixelRatio,
        scale: scale, // 添加的scale 参数
        useCORS: true,
        canvas: canvas, //自定义 canvas
        logging: true //日志开关
      };
      html2canvas(shareContent, opts).then(canvas => {
        let str;
        str = `《直播达人榜-音浪收入榜-${that.value03.split("?")[1]}》.png`;
        canvas.toBlob(
          function(blob) {
            const eleLink = document.createElement("a");
            eleLink.download = str;
            eleLink.style.display = "none";
            // 字符内容转变成blob地址
            eleLink.href = URL.createObjectURL(blob);
            // 触发点击
            document.body.appendChild(eleLink);
            eleLink.click();
            // 然后移除
            document.body.removeChild(eleLink);
          },
          "image/png",
          1
        );
        loading.close();
      });
    },
    export_data() {
      let that = this;
      let str = `排名,粉丝总数,达人,所属行业,音浪收入\n`;
      for (let i = 0; i < that.table_data01.length; i++) {
        str += `${that.table_data01[i].rowId},${that.format_num(
          that.table_data01[i].totalFans
        )},\"${that.table_data01[i].nickName.replace(/"/g, '""')}\",${
          that.table_data01[i].categoryName
        }\t,${that.format_num(that.table_data01[i].soundbyte)}\n`;
      }
      var blob = new Blob([str], { type: "text/plain;charset=utf-8" }); //解决中文乱码问题
      blob = new Blob([String.fromCharCode(0xfeff), blob], { type: blob.type });
      let object_url = window.URL.createObjectURL(blob);
      var link = document.createElement("a");
      link.href = object_url;
      let str_name = `《直播达人榜-音浪收入榜-${
        that.value03.split("?")[1]
      }》.csv`;
      link.download = str_name;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    loadMore: function() {
      if (this.page == 31) {
        return false;
      }
      this.get_data();
    },
    go_to_page01(id) {
      let router = this.$router.resolve({
        path: `/talent_main/tdetails/${id}`
      });
      window.open(router.href, "_blank");
    },
    initHeight() {
      var scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      this.isFixed = scrollTop > 180 ? true : false;
    },
    backTop() {
      document.body.scrollTop = document.documentElement.scrollTop = 0;
    }
  },
  destroyed() {
    window.removeEventListener("scroll", this.initHeight);
  }
};
</script>
<style scoped lang="less">
.data_time {
  margin-top: -52px;
  margin-bottom: 38px;
  margin-right: 0px;
  text-align: right;
  > span:first-child {
    font-size: 14px;
    color: #888888;
    letter-spacing: 0;
    // margin-right: 9px;
  }
  > span:last-child {
    font-size: 15px;
    // font-family: DINAlternate-Bold;
    letter-spacing: 0;
    color: #1779ff;
  }
}
.table {
  thead {
    tr {
      > th:nth-child(2) {
        text-align: left;
      }
    }
  }
  width: 100%;
  .tip_img {
    width: 16px;
    height: 16px;
    vertical-align: -3px;
  }
  tbody {
    tr {
      height: 78px;
    }
  }

  .td_05 {
    text-align: center;
    button {
      width: 88px;
      height: 32px;
      background-color: transparent;
      border-radius: 4px;
      border: 1px solid #fd7f2c;
      font-size: 14px;
      font-weight: normal;
      font-stretch: normal;
      line-height: 30px;
      letter-spacing: 0px;
      color: #fd7f2c;
      text-align: center;
    }
    button:hover {
      border-color: #fd924b;
      color: #ff924b;
    }
  }

  .td_01,
  .td_04 {
    font-family: DINAlternate-Bold;
    font-size: 15px;
    text-align: center;
  }
  .td_03 {
    font-size: 15px;
    text-align: center;
  }
  .td_02 {
    width: 400px;

    > div {
      section {
        width: 210px;
        > div:first-child {
          display: flex;
          align-items: center;
          > span {
            max-width: 100%;
            width: auto;
            word-break: break-all;
            font-size: 14px;
            font-weight: 600;
            color: #222;
            margin-bottom: 5px;
          }
          > span:hover {
            color: #ff924b;
          }
          img {
            width: 14px;
            height: 14px;
            margin-left: 6px;
          }
        }
        > div:last-child {
          width: 100%;
          word-break: break-all;
          font-size: 14px;
          color: #888;
        }
      }
      > img {
        border-radius: 50%;
        width: 50px;
        margin-right: 12px;
        border: 1px solid #e5e5e5;
      }
    }
  }

  .td {
    > div {
      height: 70px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
.type {
  margin-bottom: 14px;
  > div {
    display: inline-block;
  }
  .input_group {
    display: inline-block;
    margin-left: 11px;
    position: relative;
    width: 308px;
    height: 32px;
    border-radius: 4px 4px 4px 4px;
    border: solid 1px #e5e5e5;
    box-sizing: border-box;
    input {
      width: 100%;
      font-size: 14px;
      vertical-align: -1px;
      background-color: #f5f5f5;
      height: 100%;
      box-sizing: border-box;
      padding-left: 11px;
      padding-right: 38px;
      border: none;
      color: #222;
    }
    input::-webkit-input-placeholder {
      color: #b5b5b5 !important;
    }
    .imgBox:hover {
      background: url("../../../assets/wang/talentCompare/search.png") no-repeat
          12px 7px,
        #fff;
      background-size: 15px 15px;
    }
    > div {
      position: absolute;
      right: 0;
      cursor: pointer;
      top: 0px;
      text-align: center;
      width: 40px;
      height: 30px;
      border-radius: 0px 4px 4px 0px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: url("../../../assets/wang/talentCompare/search-nohover.png")
          no-repeat 12px 7px,
        #fff;
      background-size: 15px 15px;
      img {
        width: 15px;
      }
    }
  }
  .btn_group {
    text-align: right;
    float: right;
    button {
      width: 70px;
      height: 32px;
      background-color: #f8f8f8;
      border-radius: 4px;
      border: solid 1px #e6e6e6;
      font-size: 14px;
      // line-height: 30px;
      box-sizing: border-box;
      color: #222222;
      text-align: center;
    }
    > button:nth-child(1) {
      margin-right: 10px;
      img {
        width: 14px;
        vertical-align: -1px;
        margin-right: 6px;
      }
    }
    > button:nth-child(2) {
      img {
        width: 13px;
        vertical-align: -1px;
        margin-right: 6px;
      }
    }
  }
}
#talent_02 {
  padding-bottom: 1px;
  min-height: 100vh;
  width: 100%;
  .paginationBox {
    width: 100%;
    background-color: #fff;
    // margin-top: 10px;
    overflow: hidden;
    padding: 20px;
    box-sizing: border-box;
    // padding-left: 1000px;
    .el-pagination {
      float: right;
    }
  }
  // 升级会员
  .upgradeBox {
    min-height: 60vh;
    position: relative;
    .rankUpgrade {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
  }
}
.fixedThead {
  display: none;
  position: fixed;
  top: 60px;
  left: 200px;

  border-radius: 4px;
  font-size: 14px;
  font-weight: 600;
  color: #555;
  background-color: #f5f9ff;
  height: 48px;
  line-height: 48px;
  overflow: hidden;
  z-index: 99;
  font-size: 0;
  li {
    box-sizing: border-box;
    display: inline-block;
    font-size: 14px;
  }

  &.isShow {
    display: block;
  }
  img {
    width: 16px;
    height: 16px;
    vertical-align: -3px;
  }
}
[tc] {
  text-align: center;
}
[tl] {
  text-align: left;
}
[tr] {
  text-align: right;
}
</style>
